//
//  CunWuListViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/10/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "CunWuListViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "CunWu.h"
#import "CunWuContentViewController.h"
#import "MJRefresh.h"
#import "VillageAffairsManageTableVC.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface CunWuListViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    NSMutableArray *cunWuListArray;
    int contentPage;
    UITableView *cunWuTableview;
}

@end

@implementation CunWuListViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    contentPage=1;
    cunWuListArray=[[NSMutableArray alloc]init];
    self.title=@"村务公开";
    [self createTableView];
    [self addRefreshAttribute];
    [self getCunWuListInfoWithPage:1];
    
    //cell分割线顶格
    if ([cunWuTableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [cunWuTableview setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cunWuTableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [cunWuTableview setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if (self.isManager) {
        [ self createNavBtn];
    }
}

-(void)createTableView{
    
//    if (self.isManager) {
//        cunWuTableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-60) style:UITableViewStyleGrouped];
//    }else{
//        cunWuTableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140) style:UITableViewStyleGrouped];
//    }
    cunWuTableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    cunWuTableview.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    cunWuTableview.dataSource=self;
    cunWuTableview.delegate=self;
    cunWuTableview.backgroundColor=[UIColor whiteColor];
    cunWuTableview.rowHeight=55;
    [self.view addSubview:cunWuTableview];
}

#pragma mark -  导航栏按钮

-(void)createNavBtn{
    
    /*
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    */
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(writeCunWu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
}

/*
-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}
*/
#pragma mark -  发布村务

-(void)writeCunWu{
    VillageAffairsManageTableVC *publishAffairsVC = [[VillageAffairsManageTableVC alloc] init];
    publishAffairsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:publishAffairsVC animated:YES];
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    [cunWuTableview addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    [cunWuTableview addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

- (void)reloadDataToNew:(BOOL)new{
    
    if (new) {
        contentPage=1;
        [self getCunWuListInfoWithPage:1];
    }else{
        contentPage=contentPage+1;
        [self getCunWuListInfoWithPage:contentPage];
    }
}

#pragma mark - 获取村务列表

-(void)getCunWuListInfoWithPage:(int)page{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"op_cwgklist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [cunWuTableview.legendHeader endRefreshing];
        [cunWuTableview.legendFooter endRefreshing];
        
        if (![[result objectForKey:@"response"] isEqualToString:@"op_cwgklist"]) {
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"获取详情失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }
        
        NSDictionary *dataDic=[result objectForKey:@"data"];
        NSMutableArray *cunWuArray=[dataDic objectForKey:@"cwgklist"];
        if (cunWuArray.count==0) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"没有更多数据";
            [hud hide:YES afterDelay:1];
            contentPage=contentPage-1;
            [cunWuTableview.legendFooter setState:MJRefreshFooterStateNoMoreData];
            return ;
            
        }
        
        if (page==1) {
            [cunWuListArray removeAllObjects];
        }
        for (NSDictionary *dic in cunWuArray) {
            //CunWu *cunWu=[[CunWu alloc]initWithDictionary:dic];
            CunWu *cunWu=[CunWu yy_modelWithDictionary:dic];
            [cunWuListArray addObject:cunWu];
        }
        [cunWuTableview reloadData];
        
    }failureAction:^{
        
    }];
    
}

#pragma mark - UITableView代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return cunWuListArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier=@"cell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if(!cell){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    CunWu *cunWu=[cunWuListArray objectAtIndex:indexPath.row];
    UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, SCREEN_WIDTH-20, 30)];
    titleLab.text=cunWu.title;
    [cell addSubview:titleLab];
    
    UILabel *timeLab=[[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-200, 40, 190, 10)];
    timeLab.text=cunWu.addtime;
    timeLab.textAlignment=2;
    timeLab.font=[UIFont systemFontOfSize:13];
    [cell addSubview:timeLab];
    return cell;
}

#pragma mark - 进入村务详情页

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    CunWu *cunWu=[cunWuListArray objectAtIndex:indexPath.row];
    CunWuContentViewController *contentVC=[[CunWuContentViewController alloc]init];
    contentVC.itemid=cunWu.itemid;
    contentVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:contentVC animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isManager) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

#pragma mark - 删除村务

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CunWu *cunWu=[cunWuListArray objectAtIndex:indexPath.row];
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:cunWu.itemid forKey:@"itemid"];
    [CheckParams setObject:@"3" forKey:@"type"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_article.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        NSString *str=[result objectForKey:@"response"];
        
        if ([str isEqualToString:@"del_article"]) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"删除成功!";
            [hud hide:YES afterDelay:1];
            [cunWuListArray removeAllObjects];
            [cunWuTableview reloadData];
            contentPage=1;
            [self getCunWuListInfoWithPage:contentPage];
        }else{
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"删除失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }
        
        
    }failureAction:^{
        
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 1;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
